<template>
  <view class="member-list-container" :style="listHeightStylePage">
    <up-navbar title="群成员" @leftClick="closeMemberList" placeholder></up-navbar>
    <view class="member-list-content">
      <!-- 搜索框 -->
      <view class="search-bar">
        <up-input v-model="memberSearchKeyword" placeholder="搜索群成员" border="surround" clearable prefixIcon="search"
          @clear="memberSearchKeyword = ''"></up-input>
      </view>
      <view style="padding-right: 20rpx;padding-left: 20rpx;margin-bottom: 40rpx;margin-top: 20rpx;">
        <!-- 成员列表 -->
        <scroll-view scroll-y class="member-scroll-view" :style="listHeightStyle">
          <view class="member-list">

            <view v-for="(member, index) in filteredMembers" :key="index" class="member-item"
              @click="handleMemberClick(member)">
              <view v-if="source == 'Groupchathistory'" class="check">
                <up-checkbox usedAlone :checked="setChecked(member)" @change="removeAndAdd(member)"></up-checkbox>
              </view>
              <view class="member-avatar">
                <image v-if="member.avatar" :src="member.avatar" mode="aspectFill" class="avatar-image" />
                <view v-else class="avatar-text">
                  {{ showUserName(member.username) }}
                </view>
              </view>
              <view class="member-info">
                <text class="member-name">{{ member.username }}</text>
                <!-- 显示群内角色 -->
                <text class="member-role" :style="{ color: member.group_role == 99 ? '#3d85fc' : '' }"
                  v-if="member.group_role">
                  {{ getRoleText(member.group_role) }}
                </text>
              </view>
              <view v-if="Isitagroup && source !== 'Groupchathistory'" class="member-setting"
                @click.stop="memberOpen(member)">
                <view :style="{ color: member.group_role == 99 ? '#3d85fc' : '' }">
                  {{ getRoleText(member.group_role) }}
                </view>
              </view>
              <up-icon name="arrow-right" size="14" color="#999"></up-icon>
            </view>

            <view v-if="filteredMembers.length === 0" class="no-members">
              <text>未找到匹配的群成员</text>
            </view>
          </view>
        </scroll-view>
      </view>

      <view v-if="source == 'Groupchathistory'" class="Bottomselection">
        <view class="select-left">
          <text>已选择（{{ selection?.length }}）:</text>
        </view>
        <scroll-view class="scrollContainer" scroll-x>
          <view style="display: flex; width: 100%;">
            <view v-for="item in selection" :key="item.id" class="select-item">
              <up-image v-if="item.avatar" :src="item.avatar" width="100%" height="100%" radius="10rpx">
                <template #error>
                  <text>{{ showUserName(item.username) }}</text>
                </template>
              </up-image>
              <view v-else>
                <text>{{ showUserName(item.username) }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="select-right">
          <up-button @click="submit" :customStyle="{ border: 'none', width: '102rpx', height: '52rpx' }" type="primary"
            text="确定"></up-button>
        </view>
      </view>
    </view>

    <!-- 群组成员管理 -->
    <up-popup :show="memberShow" @close="memberShow = false" :round="10">
      <view class="member-popup-content" :style="memberShowHeight">
        <!-- 顶部操作栏 -->
        <view class="popup-header">
          <view class="close-btn" @click="memberShow = false">×</view>
          <view class="title">设置群身份</view>
          <view class="confirm-btn" @click="handleConfirm">确定</view>
        </view>

        <!-- 选项列表 -->
        <up-radio-group v-model="selectedRole" placement="column">
          <view class="option-item">
            <up-radio name="99" label="设为群主" :disabled="currentMember && currentMember.group_role === 99"></up-radio>
          </view>
          <view class="option-item">
            <up-radio name="98" label="设为管理员" :disabled="currentMember && currentMember.group_role === 98"></up-radio>
          </view>
          <view class="option-item">
            <up-radio name="0" label="无权限" :disabled="currentMember && currentMember.group_role === 0"></up-radio>
          </view>
        </up-radio-group>


      </view>
    </up-popup>

    <up-modal :show="memberModal" :title="memberTitle" :content="memberContent" show-cancel cancel-text="取消"
      confirm-text="确定" @confirm="memberConfirm" @cancel="memberModal = false" showCancelButton="true"
      showConfirmButton="true"></up-modal>

  </view>
</template>

<script>
import { useChatsettings, useChatStore, useGroupStore, useUserStore } from '@/pinia-store/user';
import { mapStores } from 'pinia'
import { chatApi } from '@/apis/cloud/chat';
import tuiModal from "@/components/thorui/tui-modal/tui-modal.vue"
import { getCurrentInstance } from 'vue'
export default {
  name: "Groupchatmembers",
  components: {
    tuiModal
  },
  data () {
    return {
      imgheadList: [],
      filteredMembers: [],
      memberSearchKeyword: '', // 群成员搜索关键词
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
      source: '',
      selection: [],
      imInfo: null, // 当前登录用户
      userInfo: null, // 当前用户信息
      infoId: null, // 当前用户id
      group: null, // 群信息
      memberShow: false, // 群成员管理弹窗显示状态
      memberShowHeight: {}, // 群成员管理弹窗高度
      Isitagroup: false, // 是否是群主
      selectedRole: '', // 当前选中的角色
      currentMember: null,// 当前操作的成员
      memberModal: false, // 操作群身份弹窗
      memberContent: '', // 操作群身份弹窗内容
      memberTitle: '', // 操作群身份弹窗标题
    }
  },
  onLoad (value) {
    this.source = value?.source || ''
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    this.memberShowHeight = {
      height: `${window.innerHeight - 200}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    const res = uni.getSystemInfoSync();
    this.listHeight = res.windowHeight;
    this.listHeightStylePage = {
      height: `${res.windowHeight}px`,
    };
    this.memberShowHeight = {
      height: `${res.windowHeight - 200}px`,
    };
    // #endif
    this.imInfo = this.chatStore.imInfo;// 当前登录用户
    this.userInfo = this.userStore.user;
    this.infoId = this.chatStore.imInfo.id
    this.group = this.groupStore.group;
    this.calculateListHeight()
    this.getGroupMember()
  },
  created () {
    let that = this
    const instance = getCurrentInstance().proxy;
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('Groupchathistory', async function (data) {
     that.selection =  JSON.parse(data.selection) || []
    })
  },
  computed: {
    ...mapStores(useChatStore, useUserStore, useGroupStore, useChatsettings),
    // 筛选群人员
    filteredMembers () {
      if (!this.memberSearchKeyword) {
        return this.imgheadList;
      }
      // 过滤筛选
      return this.imgheadList.filter(member => {
        return member.username.includes(this.memberSearchKeyword)
      });
    },
  },
  methods: {
    memberOpen (member) {
      this.currentMember = member;
      this.selectedRole = String(member.group_role || '0'); // 回显身份
      this.memberShow = true;
    },
    judgeInfo (imgheadList) {
      // 判断是否是群主
      this.Isitagroup = imgheadList.some(member => {
        return member.group_role && member.id === this.infoId
      });
    },
    handleConfirm () {
      if (!this.currentMember) return;

      const selected = String(this.selectedRole);
      const current = String(this.currentMember.group_role);

      // 1. 如果选择的身份与原身份相同
      if (selected == current) {
        this.memberTitle = '提示';
        this.memberContent = '该成员已经是当前身份，无需再次设置';
        this.memberModal = true;
        this.modalType = 'info'; // 普通提示
        return;
      }

      // 2. 如果选择不同身份，但不是群主转让
      if (selected !== '99') {
        this.memberTitle = selected == '98' ? '设置管理员' : '设置无权限';
        this.memberContent = `确认将 ${this.currentMember.username} 的身份设置为 ${selected === '98' ? this.getRoleText(selected) : '无权限'}？`;
        this.memberModal = true;
        this.modalType = 'confirm'; // 需要用户确认
        return;
      }

      // 3. 如果选择将群主转让给别人
      if (selected == '99') {
        this.memberTitle = '提示';
        this.memberContent = `确认将群主身份转让给 ${this.currentMember.username}？`;
        this.memberModal = true;
        this.modalType = 'confirm'; // 需要用户确认
        return;
      }
    },

    // 点击确定
    memberConfirm () {
      this.memberModal = false;
      if (this.modalType === 'confirm') {
        this.updateMemberRole();
      }
    },
    async updateMemberRole () {
      try {
        uni.showLoading({
          title: '加载中....'
        });
        const params = {
          'data[groupId]': this.group.group_id, // 群id
          'data[account]': this.imInfo.account,
          'data[memberId]': this.currentMember.id, // 群成员id
          'data[role_id]': this.selectedRole, // 群身份id
          'data[token]': this.userInfo.token,
          url: 'index.php/users/Group/ChangeGroupIdenTity.html'
        }

        const msg = await chatApi(this.userInfo.token, params);

        if (msg.code == 200) {

          this.memberShow = false
          this.getGroupMember()
          uni.setStorageSync('groupMemberUpdated', true)
          uni.showToast({
            title: '设置成功',
            icon: 'success',
          });
        } else {
          uni.showToast({
            title: '设置失败',
            icon: 'error',
          });
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '设置失败',
          icon: 'error',
        });
      }
    },
    // 是否选中
    setChecked (event) {
      const findIndex = this.selection?.findIndex(item =>  item.id == event.id );
      if (findIndex != -1) {
        return true;
      } else {
        return false;
      }
    },
    // 移除
    removeAndAdd (item) {
      const findIndex = this.selection.findIndex(i => item.id == i.id);
      if (findIndex != -1) {
        this.selection.splice(findIndex, 1); // 移除已选中的成员
      } else {

        this.selection.push(item); // 添加新成员
      }
    },
    submit () {
      uni.$emit('Groupchathistory', JSON.stringify(this.selection))
      this.closeMemberList()
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 41; // 导航栏高度（假设为 44px）
      const tabsHeight = 88;


      // #ifdef APP-PLUS
      this.listHeightStyle = {
        overflowY: 'hidden',
        height: `${this.source == 'Groupchathistory' ? this.listHeight - 198 : this.listHeight - 158}px`,
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${this.source == 'Groupchathistory' ? listHeight - 43 : listHeight}px`,
        overflowY: 'hidden',
      };
      // #endif
    },
    closeMemberList () {
      uni.navigateBack();
    },
    // 点击群成员
    handleMemberClick (member) {
      if (this.source == 'Groupchathistory') {
        const findIndex = this.selection.findIndex(i => member.id == i.id);
        if (findIndex != -1) {
          this.selection.splice(findIndex, 1); // 移除已选中的成员
        } else {
          this.selection.push(member); // 添加新成员
        }
      } else {
        uni.navigateTo({
          url: '/pages/addressBook/details/grdetails',
          animationType: 'none',
          success: function (res) {
            res.eventChannel.emit('details', {
              item: {
                id: member.wid,
                worker_name: member.username
              }
            })
          }
        });
      }
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    // 获取角色文本
    getRoleText (role) {
      return role == 99 ? '群主' : role == 98 ? '管理员' : '设置身份'
    },
    // 获取人员信息
    async getGroupMember () {
      try {
        uni.showLoading({
          title: '加载中....'
        });
        const params = {
          'data[groupId]': this.group.group_id,
          'data[account]': this.imInfo.account,
          'data[token]': this.userInfo.token,
          'data[myAccount]': this.imInfo.account,
          'data[page]': 1,
          'data[pageSize]': 1000,
          'data[friendAccount]': this.friend?.friend_account,
          url: 'index.php/users/Group/getGroupMember.html'
        }

        const msg = await chatApi(this.userInfo.token, params);

        if (msg.code == 200) {
          this.judgeInfo(msg.data)
          this.imgheadList = msg.data
          uni.hideLoading();
        }
      } catch (error) {
        uni.hideLoading();
      }
    },
  }
}
</script>



<style scoped lang="scss">
// 群成员弹窗样式
.member-list-container {
  width: 100vw;
  background-color: #f3f3f3;
  overflow-y: hidden;
  overflow-y: hidden;

  .member-list-content {
    .search-bar {
      padding: 20rpx;
      background-color: #ffffff;
      border-radius: 10rpx;
      margin-bottom: 20rpx;
    }

    .member-scroll-view {
      overflow-y: auto;
      height: calc(100vh - 200rpx);

      .member-list {
        overflow-y: auto;

        background-color: #ffffff;
        border-radius: 10rpx;

        .member-item {
          display: flex;
          align-items: center;
          padding: 20rpx;
          border-bottom: 1rpx solid #f5f5f5;

          &:last-child {
            border-bottom: none;
          }

          .member-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 10rpx;
            background-color: #3d85fc;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            margin-right: 20rpx;

            .avatar-image {
              width: 100%;
              height: 100%;
            }

            .avatar-text {
              color: #ffffff;
              font-size: 28rpx;
            }
          }

          .member-info {
            flex: 1;

            .member-name {
              font-size: 28rpx;
              color: #333;
              display: block;
              margin-bottom: 5rpx;
            }

            .member-role {
              font-size: 24rpx;
              color: #999;
            }
          }

          .member-setting {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 120rpx;
            height: 50rpx;
            border: 1px solid #E1E3E5;
            border-radius: 10px;
            color: #999;
            font-size: 26rpx;
            margin-left: 10rpx;
            margin-right: 10px;
          }

        }

        .no-members {
          text-align: center;
          padding: 40rpx 0;
          color: #999;
          font-size: 26rpx;
        }
      }
    }
  }
}

.Bottomselection {
  position: fixed;
  box-sizing: border-box;
  bottom: 0;
  padding: 20rpx 20rpx 40rpx 20rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #E1E3E5;

  .scrollContainer {
    width: 57%;

    .select-item {
      width: 60rpx;
      height: 60rpx;
      margin-right: 10rpx;
      flex-shrink: 0;

      text {
        display: inline-block;
        width: 100%;
        height: 100;
        border-radius: 10rpx;
        color: #fff;
        font-size: 20rpx;
        text-align: center;
        line-height: 60rpx;
        background-color: #3D85FC;
      }
    }
  }

  .select-left {
    font-size: 26rpx;
    width: 25%;
  }

  .select-right {
    flex: 1;
  }
}


.member-popup-content {
  background-color: #fff;
  padding: 0 30rpx;
  box-sizing: border-box;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    position: relative;

    .close-btn {
      font-size: 40rpx;
      color: #999;
      width: 40rpx;
      height: 40rpx;
      line-height: 40rpx;
    }

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      width: 200rpx;
      text-align: center;
    }


    .confirm-btn {
      font-size: 28rpx;
      color: #3D85FC;
      padding: 0 20rpx;
      height: 40rpx;
      line-height: 40rpx;
      white-space: nowrap;
    }
  }


  .option-item {
    display: flex;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #f5f5f5;

    .up-radio {
      flex: 1; // 单选框撑满一行
    }

    .up-radio__label {
      font-size: 30rpx;
      color: #333;
    }
  }

  .option-item:last-child {
    border-bottom: none;
  }

}
</style>
